package com.ybwh.outterapi.requst;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.ybwh.outterapi.codec.AppKeyHolder;
import com.ybwh.outterapi.codec.DataCrypto;
import com.ybwh.outterapi.constant.RequestHeaderProperties;
import com.ybwh.outterapi.exceptions.HashCheckerException;
import jakarta.servlet.Filter;
import jakarta.servlet.FilterChain;
import jakarta.servlet.FilterConfig;
import jakarta.servlet.ServletException;
import jakarta.servlet.ServletRequest;
import jakarta.servlet.ServletResponse;
import jakarta.servlet.http.HttpServletRequest;
import lombok.AllArgsConstructor;
import org.apache.commons.lang3.StringUtils;


import java.io.IOException;
import java.util.Objects;


/**
 * 检查hash
 */
@AllArgsConstructor
public class HashCheckRequestInputStreamFilter implements Filter {

    private DataCrypto dataCrypto;
    private ObjectMapper objectMapper;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {


        // 转换为可以多次获取流的request
        HttpServletRequest req = (HttpServletRequest) request;

        AppKeyHolder.set(req.getHeader(RequestHeaderProperties.APP_KEY));

        String checkHash = req.getHeader(RequestHeaderProperties.CHECK_HASH);
        if (StringUtils.isBlank(checkHash)) {
            // 放行
            chain.doFilter(req, response);
        }

        RereadableHttpServletRequestWrapper requestWrapper = new RereadableHttpServletRequestWrapper(req);
        byte[] data = requestWrapper.getCachedBytes();
        if (!Objects.equals(dataCrypto.hashHex(data), checkHash)) {
            throw new ServletException("hash is wrong", new HashCheckerException("hash is wrong"));
        }







        // 放行
        chain.doFilter(requestWrapper, response);
    }

    @Override
    public void destroy() {

    }
}